#!/usr/bin/env python3
"""
SchedulerAI Docker Setup Validation Script

This script validates the Docker setup without requiring Docker to be running.
It checks file structure, syntax, and configuration consistency.
"""

import os
import sys
from pathlib import Path

def check_file_exists(filepath, description):
    """Check if a file exists and report status"""
    if Path(filepath).exists():
        print(f"✓ {description}: {filepath}")
        return True
    else:
        print(f"✗ {description} missing: {filepath}")
        return False

def check_dockerfile():
    """Validate Dockerfile structure"""
    print("\n=== Dockerfile Validation ===")
    
    if not check_file_exists("Dockerfile", "Main Dockerfile"):
        return False
    
    with open("Dockerfile", "r") as f:
        content = f.read()
    
    # Check for required stages
    stages = ["base", "dependencies", "application", "runtime"]
    for stage in stages:
        if f"FROM {stage}" in content or f"as {stage}" in content:
            print(f"✓ Stage '{stage}' found")
        else:
            print(f"✗ Stage '{stage}' missing")
            return False
    
    # Check for required instructions
    required_instructions = [
        "EXPOSE 8000",
        "HEALTHCHECK",
        "USER scheduler",
        "CMD"
    ]
    
    for instruction in required_instructions:
        if instruction in content:
            print(f"✓ Instruction '{instruction}' found")
        else:
            print(f"✗ Instruction '{instruction}' missing")
            return False
    
    return True

def check_dockerignore():
    """Validate .dockerignore file"""
    print("\n=== .dockerignore Validation ===")
    
    if not check_file_exists(".dockerignore", ".dockerignore file"):
        return False
    
    with open(".dockerignore", "r") as f:
        content = f.read()
    
    # Check for important exclusions
    important_exclusions = [
        "__pycache__",
        "*.pyc",
        ".git",
        "tests/",
        "frontend/",
        "venv/",
        ".vscode/"
    ]
    
    for exclusion in important_exclusions:
        if exclusion in content:
            print(f"✓ Exclusion '{exclusion}' found")
        else:
            print(f"⚠ Exclusion '{exclusion}' missing (recommended)")
    
    return True

def check_docker_compose():
    """Validate docker-compose files"""
    print("\n=== Docker Compose Validation ===")
    
    files_to_check = [
        ("docker-compose.yml", "Development compose file"),
        ("docker-compose.prod.yml", "Production compose file")
    ]
    
    all_valid = True
    for filename, description in files_to_check:
        if check_file_exists(filename, description):
            # Basic YAML structure check
            with open(filename, "r") as f:
                content = f.read()
            
            if "version:" in content and "services:" in content:
                print(f"✓ {filename} has valid structure")
            else:
                print(f"✗ {filename} has invalid structure")
                all_valid = False
        else:
            all_valid = False
    
    return all_valid

def check_scripts():
    """Validate Docker scripts"""
    print("\n=== Docker Scripts Validation ===")
    
    scripts_to_check = [
        ("docker/start.sh", "Container startup script"),
        ("docker/health-check.sh", "Health check script"),
        ("docker/build.sh", "Build script (Linux/macOS)"),
        ("docker/build.bat", "Build script (Windows)")
    ]
    
    all_valid = True
    for filepath, description in scripts_to_check:
        if check_file_exists(filepath, description):
            # Check if script has shebang (for shell scripts)
            if filepath.endswith('.sh'):
                with open(filepath, "r") as f:
                    first_line = f.readline().strip()
                if first_line.startswith('#!'):
                    print(f"✓ {filepath} has proper shebang")
                else:
                    print(f"⚠ {filepath} missing shebang")
        else:
            all_valid = False
    
    return all_valid

def check_environment_config():
    """Validate environment configuration"""
    print("\n=== Environment Configuration Validation ===")
    
    if not check_file_exists(".env.example", "Environment template"):
        return False
    
    with open(".env.example", "r") as f:
        content = f.read()
    
    # Check for required environment variables
    required_vars = [
        "API_HOST",
        "API_PORT",
        "API_WORKERS",
        "MAX_FILE_SIZE",
        "SOLVER_TIME_LIMIT",
        "LOG_LEVEL"
    ]
    
    for var in required_vars:
        if f"{var}=" in content:
            print(f"✓ Environment variable '{var}' defined")
        else:
            print(f"✗ Environment variable '{var}' missing")
            return False
    
    return True

def check_application_files():
    """Check if required application files exist"""
    print("\n=== Application Files Validation ===")
    
    required_files = [
        ("requirements.txt", "Python dependencies"),
        ("scheduler_ai/simplified_api.py", "Main API module"),
        ("scheduler_ai/simplified_scheduler_service.py", "Scheduler service"),
        ("scheduler_ai/__init__.py", "Package init file")
    ]
    
    all_valid = True
    for filepath, description in required_files:
        if not check_file_exists(filepath, description):
            all_valid = False
    
    return all_valid

def main():
    """Main validation function"""
    print("SchedulerAI Docker Setup Validation")
    print("=" * 40)
    
    # Change to project root directory
    script_dir = Path(__file__).parent
    project_root = script_dir.parent
    os.chdir(project_root)
    
    print(f"Project root: {project_root.absolute()}")
    
    # Run all validation checks
    checks = [
        ("Application Files", check_application_files),
        ("Dockerfile", check_dockerfile),
        ("Docker Ignore", check_dockerignore),
        ("Docker Compose", check_docker_compose),
        ("Scripts", check_scripts),
        ("Environment Config", check_environment_config)
    ]
    
    passed_checks = 0
    total_checks = len(checks)
    
    for check_name, check_function in checks:
        try:
            if check_function():
                passed_checks += 1
            else:
                print(f"✗ {check_name} validation failed")
        except Exception as e:
            print(f"✗ {check_name} validation error: {e}")
    
    # Summary
    print(f"\n=== Validation Summary ===")
    print(f"Checks passed: {passed_checks}/{total_checks}")
    
    if passed_checks == total_checks:
        print("✓ All validations passed! Docker setup is ready.")
        print("\nNext steps:")
        print("1. Start Docker Desktop")
        print("2. Run: docker build -t scheduler-ai:latest .")
        print("3. Run: docker-compose up -d")
        return True
    else:
        print("✗ Some validations failed. Please fix the issues above.")
        return False

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)